package com.example.myapplication.vo;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import com.example.myapplication.until.Globals;
import com.example.myapplication.until.ImageUtils;
import com.example.myapplication.until.JBoxUtils;
import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;

import java.util.Iterator;

public class Pig extends Item{

    private int index ;

    public Pig(int index){
        this.index = index ;
    }

    private static void addPig(){
        for(int i = 0 ; i<8 ;i++){
            Pig pig = new Pig(ImageUtils.getPigIndex()) ;
            pig.setBody(JBoxUtils.createBox(Globals.PIECE_WIDTH*1.5f,Globals.PIECE_HEIGH*1.5f,Globals.PIECE_WIDTH*7f+(i*Globals.PIECE_WIDTH*1.6f),
                    Globals.PIECE_HEIGH*9f,0,JBoxUtils.PIG_TYPE,false));
            Globals.PIGLIST.add(pig);
        }
    }


    @Override
    public void drawItem(Canvas canvas, Paint paint, Point nowPosition) {
        canvas.save();
        canvas.rotate((float) (body.getAngle() * 180 / Math.PI),
                body.getPosition().x * Globals.RATE + nowPosition.x,
                body.getPosition().y * Globals.RATE + nowPosition.y);

        canvas.drawBitmap(ImageUtils.getPigImg(index), body.getPosition().x
                * Globals.RATE  + nowPosition.x, body.getPosition().y
                * Globals.RATE  + nowPosition.y, paint);

        Vec2 v = body.getPosition() ;

        canvas.restore();
    }

    public static void drewPigs(Canvas canvas,Paint paint,Point nowPosition){
        if(!Globals.PIGLIST.isEmpty()){
            Iterator<Pig> iterator = Globals.PIGLIST.iterator();
            while (iterator.hasNext()){
                Pig p = iterator.next() ;
                if(!p.isDead()){
                    Body b = p.getBody() ;
                    p.drawItem(canvas,paint,nowPosition);
                }else {
                    Globals.SCORE+=50;
                    iterator.remove();
                }
            }
        }else{
            addPig();
        }
    }

    @Override
    public void hit(Object o, float li, ContactImpulse arg1) {
        //向量 给他一个冲量
        if(o instanceof Bird){
            Vec2 v = new Vec2(-arg1.tangentImpulses[0]*1000,arg1.tangentImpulses[1]*1000);
            //System.out.println(v);
            body.applyLinearImpulse(v,body.getWorldCenter());
            //System.out.println(li);
            setLife(getLife() - li/2);
            //System.out.println(getLife());
        }
    }

    public void setBody(Body body) {
        this.body = body;
        this.body.m_userData = this;
    }
}
